package com.chentongwei.controller.user;

import com.chentongwei.cache.redis.IBasicCache;
import com.chentongwei.common.annotation.CategoryLog;
import com.chentongwei.common.annotation.DescLog;
import com.chentongwei.common.constant.ResponseEnum;
import com.chentongwei.common.entity.Result;
import com.chentongwei.common.entity.io.BaseGeetestIO;
import com.chentongwei.common.exception.WebException;
import com.chentongwei.common.util.CommonExceptionUtil;
import com.chentongwei.common.util.IPUtil;
import com.chentongwei.common.util.MD5Util;
import com.chentongwei.common.util.geetest.GeetestConstant;
import com.chentongwei.common.util.geetest.GeetestLib;
import com.chentongwei.facade.user.entity.io.LoginIO;
import com.chentongwei.facade.user.entity.io.RegistUserIO;
import com.chentongwei.facade.user.service.IUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 用户控制层接口
 *
 * @author TongWei.Chen 2017-9-17 17:36:56
 **/
@RestController
@RequestMapping("/user/user")
@CategoryLog(menu = "用户模块")
public class UserController {

    @Autowired
    private GeetestConstant geetestConstant;
    @Autowired
    private IUserService userService;
    @Autowired
    private IBasicCache basicCache;

    /**
     * 注册接口
     *
     * @param request：请求
     * @param userIO：用户信息
     * @return
     */
    @DescLog("注册")
    @PostMapping("/regist")
    public Result regist(HttpServletRequest request, @Valid RegistUserIO userIO) {
        //检查验证码
        int gtResult = /*checkGt(userIO)*/1;
        //gtResult == 1 成功
        if (gtResult == 1) {
            //检查两次输入的密码是否一致
            CommonExceptionUtil.equalsCheckThrowWebEx(userIO.getPassword(), userIO.getEnsurePassword(), ResponseEnum.PWD_AND_ENSUREPWD_NOT_SAMED);
            //加密密码
            userIO.setPassword(MD5Util.encode(userIO.getPassword()));
            //注册时的IP
            userIO.setIp(IPUtil.getIP(request));
            return userService.regist(userIO);
        } else {
            throw new WebException(ResponseEnum.GT_IS_ERROR);
        }
    }

    /**
     * 登录接口
     *
     * @param loginIO：登录信息
     * @return
     */
    @DescLog("登录")
    @PostMapping("/login")
    public Result login(@Valid LoginIO loginIO) {
        int gtResult = checkGt(loginIO);
        //gtResult == 1 成功
        if (gtResult == 1) {
            loginIO.setPassword(MD5Util.encode(loginIO.getPassword()));
            return userService.login(loginIO);
        } else {
            throw new WebException(ResponseEnum.GT_IS_ERROR);
        }
    }

    /**
     * 激活用户
     *
     * @param userId：用户id
     * @return
     */
    @PostMapping("/activeUser/{userId}")
    public Result activeUser(@PathVariable Integer userId) {
        return userService.activeUser(userId);
    }

    /**
     * 检查此邮箱是否被占用
     *
     * @param email：电子邮箱
     * @return
     */
    @GetMapping("/checkEmail")
    public Result checkEmail(String email) {
        //检查非空
        CommonExceptionUtil.strNullCheckThrowWebEx(email, ResponseEnum.EMAIL_NULL_ERROR);
        return userService.getByEmail(email);
    }

    /**
     * 检查验证码
     *
     * @param userIO
     * @return
     */
    private int checkGt(BaseGeetestIO userIO) {
        CommonExceptionUtil.nullCheckThrowWebEx(userIO.getToken(), ResponseEnum.TOKEN_IS_NULL);
        //检查验证码
        GeetestLib gtSdk = new GeetestLib(geetestConstant.getId(), geetestConstant.getKey(),
                geetestConstant.getNewfailback());
        //从redis中获取gt-server状态  //0 失败
        String gtServerStatusCode = basicCache.get(userIO.getToken() + ":" + gtSdk.gtServerStatusSessionKey);

        //从redis中获取token
        String token = basicCache.get(userIO.getToken());

        //从Redis中取出验证码信息，若没取到则代表验证码失效
        if(StringUtils.isEmpty(gtServerStatusCode) || StringUtils.isEmpty(token)) {
            throw new WebException(ResponseEnum.GT_IS_EXPIRED);
        }

        //0 失败
        int gtResult = 0;
        if ("1".equals(gtServerStatusCode)) {
            //gt-server正常，向gt-server进行二次验证
            gtResult = gtSdk.enhencedValidateRequest(userIO.getGeetestChallenge(), userIO.getGeetestValidate(), userIO.getGeetestSeccode(), token);
        } else {
            // gt-server非正常情况下，进行failback模式验证
            gtResult = gtSdk.failbackValidateRequest(userIO.getGeetestChallenge(), userIO.getGeetestValidate(), userIO.getGeetestSeccode());
        }
        return gtResult;
    }
}